package thread;

class Counter {
    private int count = 0;

    /*    public void add(){
            synchronized (this){
                count++;
            }

        }*/

    public synchronized void add() {
        count++;
    }

    public int get() {
        return count;
    }
    //synchronized与static一起使用 相当于对类对象进行加锁
    public synchronized static void fun() {
        /*等同于 synchronized (Counter.class)*/
        {
        }
    }
}

public class Demo17 {
    public static void main(String[] args) throws InterruptedException {
        //Object lucker=new Object();
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                //synchronized(lucker){
                counter.add();
                //}
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                //synchronized(lucker){
                counter.add();
                //}
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count=" + counter.get());
    }
}
